﻿using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using CashOrCard.Models;
using CashOrCard.Repository;
using CashOrCard.Extensions;

namespace CashOrCard.Controllers.Admin
{
    public class PromotionAdminController : Controller
    {
        private readonly IBaseRepository<Promotion> _promRep;
        private readonly IBaseRepository<AdvtSite> _advtSiteRepository;
        public static AdvtSite advtEntity;

        public PromotionAdminController(IBaseRepository<Promotion> promRep, IBaseRepository<AdvtSite> advtSiteRepository)
        {
            this._promRep = promRep;
            _advtSiteRepository = advtSiteRepository;
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult Index(int advtId = -1)
        {
            TempData["advtId"] = advtId;
            advtEntity = _advtSiteRepository.LoadEntities(a => a.AdvtSiteId == advtId && a.IsEnable).FirstOrDefault();
            ViewBag.advtEntity = advtEntity;
            return View();
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult GetAllPromotions(Promotion promotion)
        {
            IQueryable<Promotion> promotionList = null;

            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int advtId = Request["advtId"] == null ? -1 : Convert.ToInt32(Request["advtId"]);
            int total = 0;
            advtEntity = _advtSiteRepository.LoadEntities(a => a.AdvtSiteId == advtId && a.IsEnable).FirstOrDefault();
            if (advtEntity != null)
            {
                promotionList = advtEntity.Promotions.Where(u =>
                                                            (string.IsNullOrEmpty(promotion.PromotionName) ||
                                                             u.PromotionName.Contains(promotion.PromotionName))
                                                            &&
                                                            (promotion.StartDate == default(DateTime) ||
                                                             u.StartDate >= promotion.StartDate)
                                                            &&
                                                            (promotion.EndDate == default(DateTime) ||
                                                             u.EndDate <= promotion.EndDate) && u.isEnable)
                                                             .Skip((pageIndex - 1) * pageSize).Take(pageSize).AsQueryable();
                total = advtEntity.Promotions.Count(u => u.isEnable);
            }

            var inputList = promotionList.Select(entityPromotion => new Promotion
                                                                        {
                                                                            PromotionId = entityPromotion.PromotionId,
                                                                            PromotionBody = entityPromotion.PromotionBody,
                                                                            PromotionImagePath = entityPromotion.PromotionImagePath,
                                                                            PromotionName = entityPromotion.PromotionName,
                                                                            StartDate = entityPromotion.StartDate,
                                                                            EndDate = entityPromotion.EndDate
                                                                        }).ToList();
            var result = new { total = total, rows = inputList };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult AddNewPromotion(Promotion promotion)
        {
            int advtId = Request["advtId"] == null ? -1 : Convert.ToInt32(Request["advtId"]);
            promotion.isEnable = true;
            advtEntity = _advtSiteRepository.LoadEntities(a => a.AdvtSiteId == advtId).FirstOrDefault();
            if (advtEntity != null)
                advtEntity.Promotions.Add(promotion);

            bool added = _advtSiteRepository.Save();
            if (added)
                return Content("success");
            return Content("Some errors occured.");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult UpdatePromotion(Promotion promotion)
        {
            int advtId = Request["advtId"] == null ? -1 : Convert.ToInt32(Request["advtId"]);
            advtEntity = _advtSiteRepository.LoadEntities(a => a.AdvtSiteId == advtId).FirstOrDefault();

            var promotionEntity = advtEntity.Promotions.FirstOrDefault(p => p.PromotionId==promotion.PromotionId);
            promotionEntity.PromotionBody = promotion.PromotionBody;
            promotionEntity.PromotionName = promotion.PromotionName;
            promotionEntity.PromotionImagePath = promotion.PromotionImagePath;
            promotionEntity.StartDate = promotion.StartDate;
            promotionEntity.EndDate = promotion.EndDate;
            promotionEntity.isEnable = true;

            _advtSiteRepository.Save();

            return Content("success");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult DeletePromotion(int id)
        {
            var prom = _promRep.Get(id);
            prom.isEnable = false;
            var result = _promRep.DeleteEntities(prom);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }

        [HttpPost]
        [CashOrCardAuthorizeExtension(AllowPermissions = "sitemanagement_access", ErrorView = "PermissionDenied")]
        public string Upload(FormCollection fc)
        {
            string newFileName = string.Empty;
            if (Request.Files.Count != 0)
            {
                Thread.Sleep(500);
                HttpPostedFileBase file = Request.Files[0];

                string Extension = Path.GetExtension(file.FileName);

                newFileName = Guid.NewGuid().ToString() + Extension;

                string name = Path.Combine(Server.MapPath("/Content/Upload/"), newFileName);
                file.SaveAs(name);
            }
            Thread.Sleep(500);
            return "/Content/Upload/" + newFileName;
        }

    }
}
